// ==UserScript==
// @name         工单用户画像
// @namespace    http://tampermonkey.net/
// @version      4.4.1
// @description  工单用户画像(新版,支持会话单统计)
// @author       You
// @match        andon.oa.com/ticket/detail*
// @match        andon.cloud.tencent.com/ticket/detail*
// @match        andon.oa.com/cloud-service-im/chat*
// @match        andon.cloud.tencent.com/cloud-service-im/chat*
// @match        andon.woa.com/ticket/detail*
// @match        andon.woa.com/cloud-service-im/chat*
// @grant        none
// @require      http://libs.baidu.com/jquery/2.0.0/jquery.min.js

// ==/UserScript==

(function() {
	window.config = {
		addStyle(text) { //添加样式表到页面
			var style = document.createElement('style');
			style.type = 'text/css';
			style.innerHTML = text;
			document.getElementsByTagName('head').item(0).appendChild(style);
		},
		getQueryStr(name) { //获取url中的参数
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},
		async ajax(d){//网络请求
			let cg = {headers:{'Content-Type':'application/json'},method: d.type||'GET'};
			if(d.cookie) cg.credentials = "include";
			if(d.type == 'POST')cg.body = JSON.stringify(d.data||{});
			return (await fetch(d.url,cg)).json();
		},
		copyEle:null,
		copyText(text){//拷贝文本
			if(!config.copyEle){
				let textEle = document.createElement('textarea');
				textEle.style = 'width: 1px;height: 1px;opacity: 0;';
				document.querySelector('body').appendChild(textEle);
				config.copyEle = textEle;
			}
			config.copyEle.value = text;
			config.copyEle.select();
			if (document.execCommand('copy')) {
				console.log('复制成功');
			}
		},
		async getUserInfo(path){
			// return '';//临时紧急取消
			// if(path == '/ticket/detail'){
			// 	if(!config.userinfo)//userinfo不存在则去获取
			// 	return await config.ajax({url:`/ticket/api/tickets/${config.getQueryStr('id')}/customer?use=owner`}).then(res=>{config.userinfo = res.data;return res.data;});
			// }else{
			// 	return {uin:$(".info-item.info-item-dis span:contains('主账号UIN')").next().text()};
			// }
			// return config.userinfo;
			if(path == '/ticket/detail'){
				if(!config.userinfo){//userinfo不存在则去获取
					try{
						return await config.ajax({url:`/ticket/api/tickets/${config.getQueryStr('id')}/customer?use=owner`}).then(res=>{config.userinfo = res.data;return res.data;});
					}catch(e){//获取异常则返回空
						return {uin:''};
					}
				}
			}else{
				return {uin:$(".info-item.info-item-dis span:contains('主账号UIN')").next().text()};
			}
			return config.userinfo;
		},
		async createUl(path){//创建右侧工具栏
			$('body').append(`
			<div id="guide">
				<el-row style="position: fixed; z-index: 11;max-width: 100px; top:0; right:0; padding-right: 10px; margin-top: 50px; text-align: right;overflow: auto;max-height: 100vh;" >
					<el-col v-for="url in urls" :span="24" style="margin-bottom: 10px;"> <el-button @click="goUrl(url.url)" type="primary" size="mini" plain round>{{url.text}}</el-button> </el-col>
					<el-col :span="24"> <el-button @click="edit=true" type="info" size="mini" plain round> <i class="el-icon-s-tools"></i>设置</el-button></el-col>
				</el-row>
				<el-drawer
				  title="编辑快捷方式"
				  :visible.sync="edit"
				  direction="rtl"
					size="620px"
				  :before-close="saveEdit">
				  <div style="padding: 0 20px;overflow: auto;height: calc(100vh - 80px);">
						<el-row :gutter="20">
						  <el-col :span="24" v-for="url,index in urls">
								<el-form :inline="true" size="mini">
									<el-form-item label="快捷名称"> <el-input v-model="url.text" placeholder="建议四个字"></el-input> </el-form-item>
									<el-form-item label="url 地址"> <el-input v-model="url.url" placeholder="可动态拼接\${uin}"></el-input> </el-form-item>
									<el-form-item label="">
										<el-button type="danger" icon="el-icon-minus" @click="urls.splice(index,1)" circle ></el-button>
									</el-form-item>
								</el-form>
							</el-col>
							<el-col :span="12">
								<el-button size="mini" @click="urls.push({text:'', url:''})" icon="el-icon-circle-plus-outline" style="width: 100%;text-align: center;">增加</el-button>
							</el-col>
							<el-col :span="12">
								<el-button size="mini" type="primary" @click="saveEdit(()=>{edit=false})" icon="el-icon-check" style="width: 100%;text-align: center;">保存退出</el-button>
							</el-col>
							<el-col :span="24" style="margin-top: 18px;">
								<el-button type="text" @click="urls = urls.concat(tcbUrl)">一键新增TCB常用快捷方式</el-button>
							</el-col>
						</el-row>
					</div>
				</el-drawer>
			</div>
			`)
			new Vue({
				el:"#guide",
				data(){
					let urls = JSON.parse(localStorage[path]||'[]');
					return {
						tcbUrl:[
							{text: '云函数》',url: 'https://qcm.oa.com:8080/scf/query-function-new?rid=4&account=${uin}&accountType=uin'},
							{text: '云函数》',url: 'https://qcm.woa.com/scf/query-function-new?rid=4&account=${uin}&accountType=uin'},
							{text: '云环境》',url: 'http://cloudbase.oa.com/env-list?uin=${uin}'},
							{text: 'COS详情',url: 'http://yy.cos.oa.com/host?user=${uin}'},
							{text: 'COS详情',url: 'http://yy.cos.woa.com/host?user=${uin}'},
							{text: '社区文档',url: 'https://docs.cloudbase.net'},
							{text: '官方文档',url: 'https://cloud.tencent.com/document/product/876'},
							{text: '微信文档',url: 'https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html'},
							{text: '控制台》',url: 'https://console.cloud.tencent.com/tcb/env/overview'},
						],
						urls,
						edit:false,//编辑状态
					}
				},
				methods:{
					async goUrl(url){
						if(url.indexOf('${uin}')>-1){//链接有uin则去获取
							let userInfo = await config.getUserInfo(path);
							url = url.replace('${uin}',userInfo.uin)
						}
						window.open(url);
					},
					async saveEdit(done){
						let res = await this.$confirm('请确认是否保存更改?', '提示', {
							confirmButtonText: '立即保存',
							cancelButtonText: '先看看',
							type: 'warning'
						}).then(()=>{
							localStorage[path] = JSON.stringify(this.urls);
							this.$notify({title: '成功',message: '保存成功',duration:2000,type: 'success'});
						}).catch(()=>{});
						done();
					}
				}
			});
		},
		async allRun() { //开始运行
			new Vue({created(){config.vue = this;}});
			for (let e of this.allPages) {
				if (location.href.indexOf(e.path) > -1) {
					config.addStyle(config.commonCss + e.css||''); //写入页面样式表
					this.createUl(e.path); //创建右侧工具栏
					e.js(); //执行对应的js脚本
					break;
				}
			}
		},
		async getTipsAndData(uin){
			return '';
			return {};//特殊原因暂时停止差评分析。
			uin = uin+'';
			let showObj = {
				solve:0,//结单量
				rateNum:0,//已评价数量
				badNum:0,//差评单量
				rate4:0,//89星差评
				serveBad:0,//服务差评
				mcBad:0,//MC单差评
			};
			let isHh = true;
			try{
				let userid = localStorage.userid || await config.ajax({url:'/user?scope=ONLINE'}).then(res=>{return localStorage.userid = res.data.id;});
				let datas = await config.ajax({url:'/trpc.andon.csc.CSC/GetOverConversations',cookie:true,type:'POST',data:{"Page": 1,"Limit": 100,"Uin": uin,"ReqComm": {"LoginUid": userid}}}).then(res=>res.Conversations);
				showObj.solve += datas.length;
				for(let d of datas){
					if(d.ServiceRate){//已评价
						showObj.rateNum++;
						if(d.ServiceRate < 9){//小于9是差评
							showObj.badNum++;
							if(['1','2','3'].includes(d.ConversationUnsatisfyReason)) showObj.serveBad++;
							if(d.ServiceRate == 8) showObj.rate4++;
						}
					}
				}
			}catch(e){//没开会话
				isHh = false
			}

			let mcDatas = await config.ajax({url:'/ticket/api/tickets',cookie:true,type:'POST',data:{contact: uin, page: 1, limit: 100}}).then(res=>res.data.data);
			for(let obj of mcDatas){
				if(obj.service_channel == 39 && isHh) continue;//跳过在线售后的单
				if(obj.status == 3){//已结单
					showObj.solve ++;
					if(obj.service_rate>=1 && obj.service_rate<=5){//已评价
						showObj.rateNum ++;
						if(obj.service_rate>=1 && obj.service_rate<=4){//差评单
							showObj.mcBad++;
							showObj.badNum ++;
							if(obj.service_rate == 4){//4星差评
								showObj.rate4 ++;
							}
							if([1,2,3].includes(obj.unsatisfy_reason)){//服务差评
								showObj.serveBad ++;
							}
						}
					}
				}
			}
			

			let tips = '';
			if(showObj.solve == 0){//新提单用户
				tips += '新提单用户';
			}else{//提过单用户
				tips += `结单${showObj.solve}个 评价${showObj.rateNum}个(${Math.ceil(showObj.rateNum/showObj.solve*100)}%) | `;
				if(showObj.badNum == 0){//无差评优质客户
					tips += `无差评`;
				}else{//有差评
					tips += `差评${showObj.badNum}个(${Math.ceil(showObj.badNum/showObj.rateNum*100)}%) 服务差${showObj.serveBad}个 | 会话(${showObj.badNum-showObj.mcBad}) MC(${showObj.mcBad})`;
					if(showObj.rate4 > 0){//有四星差评的客户
						tips += ` | ${showObj.rate4}个四星`;
					}
				}
			}
			config.tipsEl = config.vue.$message({showClose: true,message: tips,type: 'warning',duration:0});
			return showObj;
		},
		commonCss: `
			::-webkit-scrollbar {width: 5px;height: 10px;}
			::-webkit-scrollbar-thumb {border-radius: 5px;-webkit-box-shadow: inset005pxrgba(0, 0, 0, 0.2);background: rgba(0, 0, 0, 0.2);}
			::-webkit-scrollbar-track {-webkit-box-shadow: inset005pxrgba(0, 0, 0, 0.2);border-radius: 0;background: rgba(0, 0, 0, 0.1);}
			ul.tools-ul {position: fixed;right: 0;top: 20px;margin: 20px;z-index: 999;list-style: none;padding: 0;font-size: 13px;}
			ul.tools-ul li {cursor: pointer;background: #fff;padding: 5px;border: 1px solid #9E9E9E;margin-bottom: 10px;transition: .3s;border-radius: 5px;line-height: 1rem;text-align: center;}
			ul.tools-ul li:not(.input-li):hover {color: #fff;background: #FF5722;border-color: #FF9800;}
			ul.tools-ul input {border: 0;padding: 5px;width: 130px;}
			ul.tools-ul input[type=date] {padding: 3px 5px;}
			ul.tools-ul li.input-li {padding: 0;}
		`,
		allPages: [
			{
				path: '/cloud-service-im/chat/',
				css:``,
				async js(){
					let oldUin = '',doing = false;
					window.setInterval(async()=>{
						if(doing) return;//处理中直接返回
						doing = true;
						let uin = $(".info-item.info-item-dis span:contains('子账号')").next().text();
						if(uin && uin != oldUin){//存在uin且和上次不相同
						    config.tipsEl&&config.tipsEl.close();
							await config.getTipsAndData(uin);
						}else if(!uin){
						    config.tipsEl&&config.tipsEl.close();
						}
						oldUin = uin;
						doing = false;
					},100);
				}
			},{
			path: '/ticket/detail',
			css: `,
				.watermark-wrapper .fixed-box {right: 30px;bottom: -60px;}
				.watermark-wrapper .fixed-box .box div {height: 40px;}
				.watermark-wrapper .fixed-box .box+.box {margin-top: 0;}
				.watermark-wrapper.fixed-box .box .el-icon-ali-copy-url {margin-bottom: 0;}
			`,
			async js(){
				let user = {};
				try{user = await config.getUserInfo('/ticket/detail');}catch(e){}
				let showObj = config.getTipsAndData(user.uin);//获取tips和数据
			}
		}]
	}
	config.allRun();
})();